const express = require('express')
const jwt = require('jsonwebtoken')
const secret="secret"
module.exports={
    createToken(str){
        let tokenKey = jwt.sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 60 * 2 ),
            data: str
        }, secret);
        return tokenKey
    },
    createToken2(str){
        let tokenKey = jwt.sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 30 ),
            data: str
        }, secret);
        return tokenKey
    },
    decode(token){
            let tokenKey
            if (token==""||token=="undefined"){
                tokenKey ={
                    status:'failed',
                    msg:"未登录，请先登录"
                }
                return tokenKey
            }
            jwt.verify(token,secret,function(err,data){
                if (err){
                    if (err.name=="TokenExpiredError"){
                        tokenKey ={
                            status:'failed',
                            msg:"授权超时"
                        }
                    }else if (err.name=="JsonWebTokenError"){
                        tokenKey ={
                            status:'failed',
                            msg:"未登录，请先登录"
                        }
                    }else {
                        tokenKey ={
                            status:'failed',
                            msg:"登录失效"
                        }
                    }
                }
                else {
                    let exp = data.exp;
                    if(!exp){
                        tokenKey ={
                            status:'failed',
                            msg:"非法访问"
                        }
                    }
                    else if(exp<(Date.now() / 1000)){
                        tokenKey ={
                            status:'failed',
                            msg:"授权超时"
                        }
                    }else {
                        tokenKey=data
                    }
                }
            })
            return tokenKey
    }
}





